from flask import Blueprint,render_template,redirect,request,url_for
from exts import db
from model.models import Dish,DishType,Order,order_dish_table,Desk

bp = Blueprint('order',__name__,url_prefix='/order')


@bp.route('/index',methods=['GET','POST'])
def index():
    if request.method == 'GET':
        desks = Desk.query.all()
        dish_types = DishType.query.all()
        return render_template('order/order_index.html',dish_types=dish_types,desks=desks)
    elif request.method == 'POST':
        desk_no = request.form.get('desk_no')
        order = Order(desk_no=desk_no)
        dish_nos = request.form.getlist('dish_nos')
        # 添加Dish对象
        for dish_no in dish_nos:
            dish = Dish.query.filter(Dish.dish_no==dish_no).first()
            order.dishes.append(dish)
        db.session.add(order)
        db.session.commit()
        return redirect(url_for("order.order_info"))


@bp.route("/order_info_detail")
def order_info_detail():
    order_no = request.args.get('order_no')
    order = Order.query.filter(Order.order_no==order_no).first()
    tot_price = 0
    for dish in order.dishes:
        tot_price += dish.price
    return render_template("order/order_info_detail.html",order=order,tot_price=tot_price)


@bp.route("/order_info")
def order_info():
    orders = Order.query.filter(Order.is_done == 0).all()
    return render_template("order/order_info.html",orders=orders)


@bp.route("/done_order")
def done_order():
    order_no = request.args.get('order_no')
    order = Order.query.filter(Order.order_no == order_no).first()
    order.is_done = 1
    db.session.commit()
    return redirect(url_for('order.order_info'))

@bp.route("/order_info_done")
def order_info_done():
    orders = Order.query.filter(Order.is_done == 1)
    return render_template("order/order_info_done.html",orders=orders)